package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Matrix;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.adapter.CommentAdapter;
import com.jml.zlhq.app.adapter.FeesAdapter;
import com.jml.zlhq.app.adapter.IBaseAdapter;
import com.jml.zlhq.app.adapter.ULikeAdapter;
import com.jml.zlhq.app.adapter.WorkTeamAdapter;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.ui.WebAppInterface.webCallBack;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.NoScrollGridView;
import com.jml.zlhq.app.widgets.NoScrollListView;
import com.jml.zlhq.app.widgets.RoundImageView;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

public class WorkDetailActivity extends BaseActivity {
	private LinearLayout pinglun,shop;
	private String id;
	private String shangjiaId;
	
	public webCallBack share,collect;
	private boolean collected = false;
	private ImageView fx;
	
	private LinearLayout infoLay;
	private ImageView top,head,zan,vip,cursor;
	private TextView title,type,price,tag,name,nametag,infoTag,infoIntro,commentTitle;
	private TextView titleTw,titleFy,titleTd,commentCount,seeCount;
	
	private TextView nodata,nocomment,nouliek;
	
	private int offset = 0;// 动画图片偏移量
	private int bmpW;// 动画图片宽度
	
	private ListView comments,fee,team;
	private IBaseAdapter commentAdapter,workTeamAdapter;
	private List<JSONObject> commentItems = new ArrayList<JSONObject>();
	private List<JSONObject> workTeamItems = new ArrayList<JSONObject>();
	private List<JSONObject> ulikeitem = new ArrayList<JSONObject>();
	private List<JSONObject> feesitem = new ArrayList<JSONObject>();
	
	private NoScrollGridView ulike;
	
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			if(msg.what==1){
				try {
					String data = msg.getData().getString("data");
					JSONObject json = new JSONObject(data);
					
					shangjiaId = BaseTools.getFrom("user._id",json);
					
					collected = !StringUtil.isEmpty(BaseTools.getFrom("is_collect",json))&&BaseTools.getFrom("is_collect",json).equals("true");
					fx.setImageResource(collected?R.drawable.ico_save_full:R.drawable.collect_selector);
					
					ImageLoader.getInstance().displayImage(BaseTools.getFrom("cover.image_url", json), top, UIUtil.getImageLoaderDisplayOptions(R.drawable.default640_320));
					title.setText(BaseTools.getFrom("title", json));
					type.setText(BaseTools.getFrom("category.subcategory", json));
					String priceStr = BaseTools.getFrom("fee", json);
					price.setText(StringUtil.isEmpty(priceStr)?"":"￥"+priceStr);
					JSONArray tags = json.getJSONArray("tags");
					String tagStr = "";
					for (int i = 0;tags!=null && i < tags.length(); i++) {
						tagStr += StringUtil.isEmpty(tagStr)?tags.getString(i):"&nbsp;&nbsp;"+tags.getString(i);
					}
					tag.setText(Html.fromHtml(tagStr));
					commentCount.setText(BaseTools.getFrom("statistic.COMMENT", json));
					seeCount.setText(BaseTools.getFrom("statistic.CLICK", json));
					name.setText(BaseTools.getFrom("user.name", json));
					nametag.setText(BaseTools.getFrom("place", json));
					ImageLoader.getInstance().displayImage(BaseTools.getFrom("user.logo_url", json), head, UIUtil.getImageLoaderDisplayOptions(R.drawable.default140));
					if(StringUtil.isEmpty(BaseTools.getFrom("user.isAwesome", json))||Integer.parseInt(BaseTools.getFrom("user.isAwesome", json))==0){
						zan.setVisibility(View.GONE);
					}else{
						zan.setVisibility(View.VISIBLE);
					}
					if(StringUtil.isEmpty(BaseTools.getFrom("user.isVerify", json))||Integer.parseInt(BaseTools.getFrom("user.isVerify", json))==0){
						vip.setVisibility(View.GONE);
					}else{
						vip.setVisibility(View.VISIBLE);
					}
					JSONArray envs = json.getJSONArray("envs");
					JSONArray colors = json.getJSONArray("colors");
					JSONArray styles = json.getJSONArray("styles");
					String infotagStr1 = "婚礼色彩:&nbsp;&nbsp;";
					for (int i = 0;colors!=null && i < colors.length(); i++) {
						infotagStr1 += StringUtil.isEmpty(infotagStr1)?colors.getString(i):"&nbsp;&nbsp;"+colors.getString(i);
					}
					String infotagStr2 = "婚礼环境:&nbsp;&nbsp;";
					for (int i = 0;envs!=null && i < envs.length(); i++) {
						infotagStr2 += StringUtil.isEmpty(infotagStr2)?envs.getString(i):"&nbsp;&nbsp;"+envs.getString(i);
					}
					String infotagStr3 = "婚礼风格:&nbsp;&nbsp;";
					for (int i = 0;styles!=null && i < styles.length(); i++) {
						infotagStr3 += StringUtil.isEmpty(infotagStr3)?styles.getString(i):"&nbsp;&nbsp;"+styles.getString(i);
					}
					String infotagStr4 = "婚礼地点:&nbsp;&nbsp;"+BaseTools.getFrom("place", json);
					
					infoTag.setText(Html.fromHtml(infotagStr4+"<br/>"+infotagStr3+"<br/>"+infotagStr2+"<br/>"+infotagStr1));
					infoIntro.setText(Html.fromHtml("&nbsp;&nbsp;&nbsp;&nbsp;"+BaseTools.getFrom("description", json)));
				
					JSONArray pics = json.getJSONArray("pics");
					final ArrayList<String> piclist = new ArrayList<String>();
					for (int i = 0;pics!=null&& i < pics.length(); i++) {
						piclist.add(BaseTools.getFrom("image_url", pics.getJSONObject(i)));
					}
					for (int i = 0;pics!=null && i < pics.length(); i++) {
						ImageView img = new ImageView(activity);
						img.setScaleType(ScaleType.CENTER_CROP);
						JSONObject imageJson = pics.getJSONObject(i);
						double wph = (double)imageJson.getInt("image_width")/(double)imageJson.getInt("image_height");
						LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,(int)(UIUtil.winWidth/wph));
						lp.setMargins(0, UIUtil.dip2px(appContext, 3), 0, 0);
						img.setLayoutParams(lp);
						ImageLoader.getInstance().displayImage(BaseTools.getFrom("image_url", imageJson), img, UIUtil.getImageLoaderDisplayOptions(R.drawable.default640_426));
						img.setTag(i);
						img.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								int index = (Integer) v.getTag();
								Intent intent = new Intent(activity, ViewPagerActivity.class);
								Bundle data = new Bundle();
								data.putSerializable("list", piclist);
								data.putInt("index", index);
								intent.putExtras(data);
								activity.startActivity(intent);
							}
						});
						infoLay.addView(img);
					}
					
					JSONArray feesThis = null;
					try {
						feesThis = json.getJSONArray("fees");
					} catch (Exception e) {}
					feesitem.clear();
					for (int i = 0;feesThis!=null && i < feesThis.length(); i++) {
						feesitem.add(feesThis.getJSONObject(i));
					}
					fee.setAdapter(new FeesAdapter(activity, feesitem));
					
					JSONArray moreLikeThis = null;
					try {
						moreLikeThis = json.getJSONArray("more_like_this");
					} catch (Exception e) {}
					ulikeitem.clear();
					for (int i = 0;moreLikeThis!=null && i < moreLikeThis.length(); i++) {
						ulikeitem.add(moreLikeThis.getJSONObject(i));
					}
					ulike.setAdapter(new ULikeAdapter(activity, ulikeitem));
					commentTitle.setText(BaseTools.getFrom("statistic.COMMENT", json)+"条评论");
					nouliek.setVisibility(ulikeitem.isEmpty()?View.VISIBLE:View.GONE);
					
					workTeamItems.clear();
					JSONArray workTeamjson = null;
					try {
						workTeamjson = json.getJSONArray("teams");
					} catch (Exception e) {}
					for (int i = 0;workTeamjson!=null && i < workTeamjson.length(); i++) {
						workTeamItems.add(workTeamjson.getJSONObject(i));
					}
					workTeamAdapter.notifyDataSetChanged();
					
					commentItems.clear();
					JSONArray commentsjson = null;
					try {
						commentsjson = json.getJSONArray("comments");
					} catch (Exception e) {}
					for (int i = 0;commentsjson!=null && i < commentsjson.length(); i++) {
						commentItems.add(commentsjson.getJSONObject(i));
					}
					commentAdapter.notifyDataSetChanged();
					nocomment.setVisibility(commentItems.isEmpty()?View.VISIBLE:View.GONE);
					
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.work_detail_activity);
		
		((ScrollView)findViewById(R.id.work_detail_scroll)).smoothScrollTo(0, 0);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setImageResource(R.drawable.share_selector);
		fx = (ImageView) findViewById(R.id.content_header_right_img2);
		fx.setVisibility(View.VISIBLE);
		fx.setImageResource(R.drawable.collect_selector);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setVisibility(View.INVISIBLE);
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		
		roghtImage1.setOnClickListener(this);
		fx.setOnClickListener(this);
		
		
		pinglun = (LinearLayout) findViewById(R.id.work_detail_pinglun);
		shop = (LinearLayout) findViewById(R.id.work_detail_shop);
		top = (ImageView) findViewById(R.id.work_detail_image);
		int height = UIUtil.winWidth*320/640;
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, height);
		top.setLayoutParams(lp);
		title = (TextView) findViewById(R.id.work_detail_title);
		type = (TextView) findViewById(R.id.work_detail_type);
		price = (TextView) findViewById(R.id.work_detail_price);
		name = (TextView) findViewById(R.id.work_detail_name);
		tag = (TextView) findViewById(R.id.work_detail_tag);
		nametag = (TextView) findViewById(R.id.work_detail_name_tag);
		head = (RoundImageView) findViewById(R.id.work_detail_head);
		zan = (ImageView) findViewById(R.id.work_detail_zan);
		vip = (ImageView) findViewById(R.id.work_detail_v);
		infoLay = (LinearLayout) findViewById(R.id.work_detail_info);
		infoTag = (TextView) findViewById(R.id.work_detail_info_tag);
		commentCount = (TextView) findViewById(R.id.work_detail_comment_count);
		seeCount = (TextView) findViewById(R.id.work_detail_see_count);
		infoIntro = (TextView) findViewById(R.id.work_detail_info_intro);
		ulike = (NoScrollGridView) findViewById(R.id.work_detail_ulike);
		commentTitle = (TextView) findViewById(R.id.work_detail_comment_title);
		comments = (NoScrollListView) findViewById(R.id.work_detail_comment);
		commentAdapter = new CommentAdapter(activity, commentItems,false);
		comments.setAdapter(commentAdapter);
		ulike.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				int position = new Long(arg3).intValue();
				JSONObject json = ulikeitem.get(position);
				if(!StringUtil.isEmpty(BaseTools.getFrom("_id",json))&&!BaseTools.getFrom("_id",json).equals("-1")){
					Bundle data = new Bundle();
					data.putString("id", BaseTools.getFrom("_id",json));
					UIUtil.openActivity(activity, WorkDetailActivity.class, data);
				}else{
					UIUtil.ToastMessage(activity, "未找到该作品信息");
				}
			}
		});
		
		fee = (NoScrollListView) findViewById(R.id.work_detail_fee);
		team = (NoScrollListView) findViewById(R.id.work_detail_team);
		
		nodata = (TextView) findViewById(R.id.work_detail_nodata);
		nocomment = (TextView) findViewById(R.id.work_detail_nocomment);
		nouliek = (TextView) findViewById(R.id.work_detail_noulike);
		
		workTeamAdapter = new WorkTeamAdapter(activity, workTeamItems);
		team.setAdapter(workTeamAdapter);
		team.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				int position = new Long(arg3).intValue();
				JSONObject json = workTeamItems.get(position);
				if(!StringUtil.isEmpty(BaseTools.getFrom("_id",json))&&!BaseTools.getFrom("_id",json).equals("-1")){
					Bundle data = new Bundle();
					data.putString("id", BaseTools.getFrom("_id",json));
					UIUtil.openActivity(activity, TeamDetailActivity.class, data);
				}else{
					UIUtil.ToastMessage(activity, "未找到该团队信息");
				}
			}
		});
		
		titleTw = (TextView) findViewById(R.id.work_detail_tw_title);
		titleFy = (TextView) findViewById(R.id.work_detail_fy_title);
		titleTd = (TextView) findViewById(R.id.work_detail_td_title);
		
		cursor = (ImageView) findViewById(R.id.work_detail_bar);
		
		GradientDrawable gd = new GradientDrawable();//创建drawable
	    gd.setColor(getResources().getColor(R.color.color_e95847));
	    gd.setSize((UIUtil.winWidth-UIUtil.dip2px(appContext, 20))/3, UIUtil.dip2px(appContext, 3));
	    cursor.setImageDrawable(gd);
		bmpW = (UIUtil.winWidth-UIUtil.dip2px(appContext, 20))/3;// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		offset = (screenW / 3 - bmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// 设置动画初始位置
		
		tabSelect(0);
		titleTw.setOnClickListener(this);
		titleFy.setOnClickListener(this);
		titleTd.setOnClickListener(this);
				
		pinglun.setOnClickListener(this);
		shop.setOnClickListener(this);
		
		
		//if()
		//if(crowdUrl!=null&&crowdUrl.contains("/map"))crowdUrl = "http://192.168.1.254:8080/"+crowdUrl.substring(crowdUrl.indexOf("/map"));
		try {
			id = getIntent().getExtras().getString("id");
		} catch (Exception e) {
			e.printStackTrace();
		}
		 
		share = new webCallBack() {
			@Override
			public void call(Object str) {
				UIUtil.showLoadingDialog(WorkDetailActivity.this, "加载中，请稍后...", false);
				appContext.showShare(URLs.SHARE_WORK+"?id="+id);
			}
		};
		collect = new webCallBack() {
			@Override
			public void call(Object str) {
				if(!appContext.isLogin()){
					UIUtil.openActivity(WorkDetailActivity.this, LoginActivity.class, null,1);
				}else{
					Map<String, String> map = new HashMap<String, String>();
					map.put("auth_token", appContext.getLoginUid());
					map.put("target_id", id);
					final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "提交中，请稍后...", false);
					HttpService.postByText(collected?URLs.COLLECT_CANCEL_WORK:URLs.COLLECT_WORK, map, new TextHttpResponseHandler() {
						
						@Override
						public void onSuccess(int arg0, Header[] arg1, String arg2) {
							mProDialog.dismiss();
							try {
								JSONObject result = new JSONObject(arg2);
								if(result.getInt("status")==0){
									UIUtil.ToastMessage(activity, collected?"取消收藏成功":"收藏成功");
									collected = !collected;
									fx.setImageResource(collected?R.drawable.ico_save_full:R.drawable.collect_selector);
								}else{
									UIUtil.ToastMessage(activity, result.getString("message"));
								}
							} catch (JSONException e) {
								e.printStackTrace();
								UIUtil.ToastMessage(activity, collected?"取消收藏失败":"收藏失败");
							}
						}
						
						@Override
						public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
							mProDialog.dismiss();
							UIUtil.ToastMessage(activity, collected?"取消收藏失败":"收藏失败");
						}
					});
				}
			}
		};
		
		urlParam = new HashMap<String, String>();
		urlParam.put("id", id);
		loadData(urlParam);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==1&&appContext.isLogin()){
			loadData(urlParam);
//			url = url+"&auth_token="+appContext.getLoginUid();
//			Log.i("==web url==", url);
//			webView.loadUrl(url);  
		}
		if(requestCode==2&&resultCode==Activity.RESULT_OK&&null!=data){
			
			try {
				String pinlun = data.getStringExtra("comment");
				commentItems.add(0, new JSONObject(pinlun));
				commentAdapter.notifyDataSetChanged();
				commentTitle.setText(commentItems.size()+"条评论");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
//			handler.post(new Runnable() {
//				@Override
//				public void run() {
//					if(BuildConfig.DEBUG)Log.i("==comment==", data.getStringExtra("comment"));
//					webView.loadUrl("javascript:newComment('"+data.getStringExtra("comment")+"')");
//				}
//			});
		}
	}
	
	

	@Override
	public void loadData(Map<String, String> param) {
		param.put("auth_token", appContext.getLoginUid());
		HttpService.getByText(URLs.WORK_DETAIL, param, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, String resultStr) {
				try {
					if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
					JSONObject result = new JSONObject(resultStr);
					if(result.getInt("status")==0){
						Message  msg = new Message();
						Bundle data = new Bundle();
						data.putString("data", result.getJSONObject("data").toString());
						msg.setData(data);
						msg.what=1;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				UIUtil.ToastMessage(activity, "抱歉，访问失败");
			}
		});
	}

	@Override
	public void clearData() {}
	
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.work_detail_pinglun:
			Bundle bdl = new Bundle();
			bdl.putInt("type", 1);
			bdl.putString("id", id);
			UIUtil.openActivity(this, PinglunActivity.class, bdl, 2);
			break;
		case R.id.content_header_right_img:
			if(share!=null)share.call(null);
			break;
		case R.id.content_header_right_img2:
			if(collect!=null)collect.call(null);
			break;
		case R.id.work_detail_shop:
			try {
				if(StringUtil.isEmpty(shangjiaId)||shangjiaId.equals("-1")){
					UIUtil.ToastMessage(activity, "暂无该商家信息");
				}else{
					Bundle data = new Bundle();
					data.putString("id", shangjiaId);
					UIUtil.openActivity(activity, TeamDetailActivity.class, data);
				}
			} catch (Exception e) {
				UIUtil.ToastMessage(activity, "暂无该商家信息");
			}
			
			break;
		case R.id.work_detail_tw_title:
			tabSelect(0);
			break;
		case R.id.work_detail_fy_title:
			tabSelect(1);
			break;
		case R.id.work_detail_td_title:
			tabSelect(2);
			break;
		default:
			break;
		}
	}
	
	
	private void tabSelect(int index){
		nodata.setVisibility(View.GONE);
		TextPaint paintTw = titleTw.getPaint();
		TextPaint paintFy = titleFy.getPaint();
		TextPaint paintTd = titleTd.getPaint();
		
		int currIndex = -1;
		if(paintTw.isFakeBoldText())currIndex=0;
		if(paintFy.isFakeBoldText())currIndex=1;
		if(paintTd.isFakeBoldText())currIndex=2;
		if(index==currIndex)return;
		currIndex=currIndex<0?0:currIndex;
		
		int one = offset * 2 + bmpW;
		Animation animation = new TranslateAnimation(one*currIndex, one*index, 0, 0);
		animation.setFillAfter(true);// True:图片停在动画结束位置
		animation.setDuration(300);
		cursor.startAnimation(animation);
			
		titleTw.setTextColor(getResources().getColor(R.color.color_78));
		titleFy.setTextColor(getResources().getColor(R.color.color_78));
		titleTd.setTextColor(getResources().getColor(R.color.color_78));
		
		infoLay.setVisibility(View.GONE);
		fee.setVisibility(View.GONE);
		team.setVisibility(View.GONE);
		
		paintTw.setFakeBoldText(false);
		paintFy.setFakeBoldText(false);
		paintTd.setFakeBoldText(false);
		if(index==0){
			infoLay.setVisibility(View.VISIBLE);
			titleTw.setTextColor(getResources().getColor(R.color.color_ff96b0));
			paintTw.setFakeBoldText(true);
		}
		if(index==1){
			nodata.setVisibility(feesitem.isEmpty()?View.VISIBLE:View.GONE);
			fee.setVisibility(View.VISIBLE);
			titleFy.setTextColor(getResources().getColor(R.color.color_ff96b0));
			paintFy.setFakeBoldText(true);
		}
		if(index==2){
			nodata.setVisibility(workTeamItems.isEmpty()?View.VISIBLE:View.GONE);
			team.setVisibility(View.VISIBLE);
			titleTd.setTextColor(getResources().getColor(R.color.color_ff96b0));
			paintTd.setFakeBoldText(true);
		}
	}
}
